package com.attendance.www.hr.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import com.attendance.www.hr.beans.AttachmentBean;
import com.attendance.www.hr.dao.mapper.CorporationMapper;
import com.attendance.www.hr.dao.mapper.EmployeeCorporationMapper;
import com.attendance.www.hr.dao.mapper.EmployeeMapper;
import com.attendance.www.hr.entitys.Corporation;
import com.attendance.www.hr.entitys.CorporationExample;
import com.attendance.www.hr.entitys.Employee;
import com.attendance.www.hr.entitys.EmployeeCorporation;
import com.attendance.www.hr.entitys.EmployeeCorporationExample;
import com.attendance.www.hr.entitys.EmployeeDepartment;
import com.attendance.www.hr.entitys.EmployeeExample;
import com.attendance.www.hr.exception.ResultFaultException;
import com.attendance.www.hr.service.IEmployeeCorporationExcelService;

@Service
public class EmployeeCorporationExcelServiceImpl implements IEmployeeCorporationExcelService {

	@Resource
	private EmployeeCorporationMapper employeeCorporationDao;
	@Resource
	private EmployeeMapper employeeDao;
	@Resource
	private CorporationMapper CorporationDao;

	private Map<Integer,Integer> addEmployeeCorporationMap;
	
	private Map<String,Employee> employeeMap;
	
	private Map<String,Corporation> corporationMap;
	
	private Map<Integer, String> employeeIdMap;
	
	private Map<Integer, Integer> isEmployeeCorporationMap;

	/**
	 * 删除岗位相关信息
	 * 
	 * @return
	 */
	@Override
	public boolean delEmployeeCorporation() {
		return true;
	}

	@Override
	public List<String> importEmployeeCorporation(Workbook work, AttachmentBean attachmentBean) {
		Calendar calendar = Calendar.getInstance(); // 得到日历
		calendar.setTime(attachmentBean.getFromDate());// 把当前时间赋给日历
		calendar.add(Calendar.DAY_OF_MONTH, -1); // 设置为前一天
		Date ThruDate = calendar.getTime(); // 得到前一天的时间
		Date oldThruDate = null;
		if (attachmentBean.getType() == 3) {
			EmployeeCorporationExample example = new EmployeeCorporationExample();
			EmployeeCorporationExample.Criteria criteria = example.createCriteria();
			criteria.andThruDateIsNull();
			EmployeeCorporation employeeCorporation = new EmployeeCorporation();
			employeeCorporation.setThruDate(ThruDate);
			employeeCorporationDao.updateByExampleSelective(employeeCorporation, example);
		}
		
		
		addEmployeeCorporationMap = new HashMap<Integer,Integer>();
		employeeMap= new HashMap<String,Employee>();
		corporationMap= new HashMap<String,Corporation>();
		employeeIdMap =  new HashMap<Integer, String>();
		isEmployeeCorporationMap=  new HashMap<Integer, Integer>();
		List<String> successList = new ArrayList<String>();

		// 判断导入类型 1.覆盖 2.增量
		EmployeeCorporationExample example =new EmployeeCorporationExample();
        example.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate()).andThruDateIsNull().andIsCorporationEqualTo(0);
        example.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate()).andThruDateGreaterThanOrEqualTo(attachmentBean.getFromDate()).andIsCorporationEqualTo(0);
		List<EmployeeCorporation> employeeCorporationList = employeeCorporationDao.selectByExample(example);
		for(EmployeeCorporation employeeCorporation:employeeCorporationList){
			addEmployeeCorporationMap.put(employeeCorporation.getEmployeeId(), -1);
			oldThruDate = employeeCorporation.getThruDate();
		}
		EmployeeExample employeeExample =new EmployeeExample();
		employeeExample.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate()).andThruDateIsNull().andEmployeeIsSeparatedEqualTo(0);
		employeeExample.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate()).andThruDateGreaterThanOrEqualTo(attachmentBean.getFromDate()).andEmployeeIsSeparatedEqualTo(0);

		List<Employee> employeeList = employeeDao.selectByExample(employeeExample);
		for(Employee employee:employeeList){
			employeeMap.put(employee.getEmployeeNo(), employee);
			employeeIdMap.put(employee.getEmployeeId(), employee.getEmployeeNo());
		}
		
		CorporationExample corporationExample =new CorporationExample();
		corporationExample.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate()).andThruDateIsNull().andIsDeleteEqualTo(0);
		corporationExample.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate()).andThruDateGreaterThanOrEqualTo(attachmentBean.getFromDate()).andIsDeleteEqualTo(0);
		List<Corporation> corporationList = CorporationDao.selectByExample(corporationExample);
		for(Corporation corporation:corporationList){
			corporationMap.put(corporation.getCorporationCode(), corporation);
		}
		
		// 获取工作表的数量
		int sheetNum = work.getNumberOfSheets();
		// 遍历工作表 找出要导入的Excel表
		for (int m = 0; m < sheetNum; m++) {
			Sheet sh = work.getSheetAt(m);
			if (sh.getSheetName().equals("1.2员工与公司关系")) {
				Sheet sheet = work.getSheetAt(m);
				List<String> errorMsgList = new ArrayList<String>();// 创建错误信息列表
				// 扫描Excel每行的每个单元格
				for (int i = 1; i <= sheet.getLastRowNum(); i++) {
					EmployeeCorporation employeeCorporation = new EmployeeCorporation();// 创建岗位对象
					StringBuilder str = new StringBuilder("第" + (i + 1) + "行");
					Row row = sheet.getRow(i);
					// 如果一整行为空则忽略此行继续遍历
					if (row == null) {
						continue;
					}
					// 遍历某一行的所有列，如果此行每列都为空则跳过继续下一行
					boolean isNull = true;
					for (int c = 0; c < row.getLastCellNum(); c++) {
						if (row.getCell(c) == null || StringUtils.isBlank(row.getCell(c).toString())) {
							continue;
						} else {
							isNull = false;
						}
					}
					if (isNull) {
						continue;
					}
					if (oldThruDate != null) {
						if (oldThruDate.getTime() >= attachmentBean.getFromDate().getTime()) {
							employeeCorporation.setThruDate(oldThruDate);
						}
					}
					employeeCorporation.setFromDate(attachmentBean.getFromDate());

					// 判断第一列员工编码的合法性
					if (row.getCell(0) != null && StringUtils.isNotBlank(row.getCell(0).toString())) {
						String employeeNo = row.getCell(0).toString();
						// 判断是否为数字
						if (row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
							employeeNo = new BigDecimal(row.getCell(0).getNumericCellValue()).intValue()+"";
						}else{
							employeeNo = row.getCell(0).toString();
						}
						if(employeeMap.containsKey(employeeNo)){
							employeeCorporation.setEmployeeId(employeeMap.get(employeeNo).getEmployeeId());
							if(addEmployeeCorporationMap.containsKey(employeeMap.get(employeeNo).getEmployeeId())){
								if(addEmployeeCorporationMap.get(employeeMap.get(employeeNo).getEmployeeId())<0){
									if(attachmentBean.getType()==2) {
										str.append("员工号"+employeeNo+"已存在,");
									}
								}else{
									str.append( "与第" + addEmployeeCorporationMap.get(employeeMap.get(employeeNo).getEmployeeId()) + "行员工编码(" + employeeNo + ")已存在,");
								}
							}else{
								employeeCorporation.setEmployeeId(employeeMap.get(employeeNo).getEmployeeId());
							}
						}else{
							str.append("员工号不存在,");
						}
					} else {
						str.append("员工号不能为空,");
					}
					
					// 判断第二列公司编码的合法性
					if (row.getCell(2) != null && StringUtils.isNotBlank(row.getCell(2).toString())) {
						String corporationNo = row.getCell(2).toString();
						if(corporationMap.containsKey(corporationNo)){
							employeeCorporation.setCorporationId(corporationMap.get(corporationNo).getCorporationId());
						}else{
							str.append("公司编码不存在,");
						}
					} else {
						str.append("公司编码不能为空,");
					}
					// 判断第三列开始日期
					if (row.getCell(4) != null && StringUtils.isNotBlank(row.getCell(4).toString())) {
						Date fromDate = new Date();
						try{
							fromDate = row.getCell(4).getDateCellValue();
						}catch (Exception e) {
							str.append("开始日期格式不正确,");
						}
						if(fromDate !=null){
							employeeCorporation.setFromDate(fromDate);
						}else{
							str.append("开始日期格式不正确,");
						}
					}else{
						str.append("开始日期不能为空,");
					}
					
					// 判断第四列结束日期
					if (row.getCell(5) != null && StringUtils.isNotBlank(row.getCell(5).toString())) {
						Date fromDate = new Date();
						try{
							fromDate = row.getCell(5).getDateCellValue();
						}catch (Exception e) {
							str.append("结束日期格式不正确,");
						}
						if(fromDate !=null){
							employeeCorporation.setThruDate(fromDate);
						}else{
							str.append("结束日期格式不正确,");
						}
					}
					employeeCorporation.setIsCorporation(0);
					if(employeeCorporation.getFromDate()!=null&&employeeCorporation.getThruDate()!=null)
						if(employeeCorporation.getFromDate().getTime()>employeeCorporation.getThruDate().getTime()){
							str.append("开始日期大于结束日期,");
						}
					if (str.length() == new String("第" + (i + 1) + "行").length()) {
						boolean a=true;
						// 判断导入类型 1.覆盖 2.增量
						if (attachmentBean.getType()==1) {
							EmployeeCorporationExample employeeCorporationExample =new EmployeeCorporationExample();
							employeeCorporationExample.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate()).andThruDateIsNull().andIsCorporationEqualTo(0).andEmployeeIdEqualTo(employeeCorporation.getEmployeeId());
							employeeCorporationExample.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate()).andThruDateGreaterThanOrEqualTo(attachmentBean.getFromDate()).andIsCorporationEqualTo(0).andEmployeeIdEqualTo(employeeCorporation.getEmployeeId());
							employeeCorporationDao.updateByExampleSelective(employeeCorporation, employeeCorporationExample);
							String employeeNo = row.getCell(0).toString();
							// 判断是否为数字
							if (row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
								employeeNo = new BigDecimal(row.getCell(0).getNumericCellValue()).intValue()+"";
							}else{
								employeeNo = row.getCell(0).toString();
							}
							String success = str.toString() + "员工编码(" +  employeeNo+ ")";
							successList.add(success);
							a=false;
						} 
						if(a) {
							employeeCorporationDao.insertSelective(employeeCorporation);
							addEmployeeCorporationMap.put(employeeCorporation.getEmployeeId(), i+1);
						}
						
					} else {
						String errorStr = str.toString().substring(0, str.toString().length() - 1);
						errorMsgList.add(errorStr);
					}
				}
				List<EmployeeCorporation> employeeCorporationList2 = employeeCorporationDao.selectByExample(example);
				for (Employee employee : employeeList) {
					isEmployeeCorporationMap.put(employee.getEmployeeId(), 0);
				}
				for(EmployeeCorporation employeeCorporation:employeeCorporationList2) {
					isEmployeeCorporationMap.put(employeeCorporation.getEmployeeId(), 1);
				}
				for (Integer in : isEmployeeCorporationMap.keySet()) {
					// map.keySet()返回的是所有key的值

					Integer str = isEmployeeCorporationMap.get(in);// 得到每个key多对用value的值
					if (str == 0) {
						String errorStr = "员工编码(" + employeeIdMap.get(in) + ")未设置公司!";
						errorMsgList.add(errorStr);
					}
				}
				if (errorMsgList.size() > 0) {
					throw new ResultFaultException("9_00003", errorMsgList);
				}

				if (successList.size() > 0) {
					successList.add(0, "员工与公司导入完成,并覆盖数据如下：");
				} else {
					successList.add(0, "员工与公司导入完成");
				}
				return successList;
			}
		}
		throw new ResultFaultException("9_00013");
	}
}
